using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace SpoonStream
{
	public class Streamer
	{
		private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		private byte[] _buffer = new byte[ulong.MaxValue];
		private EndPoint _endPoint = new IPEndPoint(IPAddress.Any, 0);
		private SocketFlags _flags = SocketFlags.None;
		private IPPacketInformation _packetInfo;

		private StreamHandler _handler;

		public Streamer()
		{
			_handler = new StreamHandler(this);
			_socket.Bind(new IPEndPoint(IPAddress.Any, 0));
			_socket.BeginReceiveMessageFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref _endPoint,
											new AsyncCallback(ReceiveMessage), null);
		}

		private void ReceiveMessage(IAsyncResult ar)
		{
			int count = _socket.EndReceiveMessageFrom(ar, ref _flags, ref _endPoint, out _packetInfo);
			byte[] data = new byte[count];
			Array.Copy(_buffer, data, count);

			_handler.ReceiveMessage((IPEndPoint) _endPoint, data);

			_socket.BeginReceiveMessageFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref _endPoint,
											new AsyncCallback(ReceiveMessage), null);
		}

		public int Port
		{
			get { return ((IPEndPoint)_socket.LocalEndPoint).Port; }
		}
	}
}
